package controllers

import (
	"api/cache"
	"api/models"
	"api/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {

	phone := c.GetString("phone")
	password := c.GetString("password")

	//1-判断用户名和密码是否为空
	if phone == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "手机号 或者 密码为空",
		}
		c.ServeJSON()
		return
	}

	loginErrorRedisKey := "login_error" + phone
	errCount, _ := cache.Rdb.Get(cache.Ctx, loginErrorRedisKey).Int()
	if errCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误3次禁止登录",
		}
		c.ServeJSON()
		return
	}

	//2-根据用户名信息查询数据库，是否有用户
	var user models.User
	models.DB.Table("users").Where("phone = ?", phone).First(&user)
	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "手机号不存在",
		}
		c.ServeJSON()
		return
	}

	//3-密码是否正确
	if user.Password != pkg.Md5Str(password) {

		cache.Rdb.Incr(cache.Ctx, loginErrorRedisKey)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, loginErrorRedisKey, 3, time.Hour*2)
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "密码错误次数3次，封禁2个小时",
			}
			c.ServeJSON()
			return
		}

		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}

	cache.Rdb.Del(cache.Ctx, loginErrorRedisKey) //登录成功，清空密码错误次数
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return

}
